package grammer.objectMatcher;

import grammer.*;
import grammer.phrase.Phrase;
import grammer.phrase.PhraseBuilder;
import grammer.phrase.PhraseEvaluator;

import java.util.Vector;

import locations.LocationArchive;

import person.PersonAchive;

import action.ActionBuilder;
import action.ActionPool;
import actionId.ActionIdGenerator;

/**
 * 
 * @author Minodor
 * 
 *         Creates an Action from a line of the scenario
 */

public class TokenMatcher {

	private ActionBuilder ab;
	private Vector<String> currentLine;
	private PhraseBuilder pBuilder;
	private PhraseEvaluator pEvaluator;
	
	//added to be able to access it from ScenarioBuilder (and then from the main method)
	private ActionIdGenerator actionIdGen;

	public TokenMatcher() {
		pBuilder = new PhraseBuilder();
		pEvaluator = new PhraseEvaluator();
		ab = new ActionBuilder();
	}

	public boolean Handle(Vector<String> currentLine, int line) {

		Phrase nextPhrase = pBuilder.buildPhrase(currentLine, line);
		if(nextPhrase!=null){
			int result = pEvaluator.eval(nextPhrase);
			if( result!=(-1)){
				ab.createAction(nextPhrase, result);
				//generate action ids for entered scenario lines
				actionIdGen = generateActionIds(nextPhrase);
				return true;
			}
			else return false;}
		else return false;
	}

	public boolean startsWith(String string) {
		if (currentLine.get(0).equalsIgnoreCase(string))
			return true;
		return false;
	}
	
	/**
	 * used to generate the action id based on the parsed scenario line ---> phrase
	 * @param phrase -> a parsed line of the scenario
	 * @return an actionIdGenerator object
	 */
	public ActionIdGenerator generateActionIds(Phrase phrase)
	{
	    Subject s = phrase.getSubject();
	    Predicate p = phrase.getPredicate();
	    LocalObject l = phrase.getLocalObject();
	    DirectObject d = phrase.getDirectObject();
	    ModalObject m = phrase.getModalObject();
	    
	    int p_i = (p!=null?p.getPredicate().ordinal():0);
	    int d_i = (d!=null?d.getObject().ordinal():0);
	    int m_i = (m!=null?m.getObject().ordinal():0);
	    
	    int s_i = -1;
	    if (s != null)
	    {
	    	s_i = PersonAchive.getPersonIndex(s.getName());
	    }
	    if (s_i == -1) s_i = 0;
	    int l_i = -1;
	    if (l != null) 
	    {
	    	l_i= LocationArchive.getInstance().getIndexOfLocation(l.getLocation());
	    }
	    //alternative. i don't know the difference yet
	    //RoomType rr = RoomType.ROOM;
	    //l_i = rr.getRoom(l.getLocation()).ordinal();
	    if (l_i == -1) l_i = 0;
	    
	    ActionIdGenerator pc = new ActionIdGenerator(s_i, p_i, l_i, m_i, d_i);
	    String day = ActionPool.getCurrentDate();
	    pc.setTimestamp(day.concat(""));
	    pc.setName(phrase.toString().replace("_X", " " + day.concat("")));
	    
	    return pc;
	}
	
	public ActionIdGenerator getActionIdGen()
	{
		return actionIdGen;
	}
}
